#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
using namespace std;

bool GetQueryString(std::string &out) {
    // 从环境变量中获取method
    string method = getenv("METHOD");
    cerr << "DEBUG METHOD: " << method << endl;
    string query_string;
    string body;
    if ("GET" == method) {
        // 从环境变量中获取url中传进来的参数parameters
        query_string = getenv("QUERY_STRING");
        out = query_string;
        // cerr << "GET DEBUG QUERY_STRING: " << query_string << endl;
    } else if ("POST" == method) {
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char ch;
        while (content_length) {
            ssize_t s = read(0, &ch, 1);
            if (s > 0) {
                body.push_back(ch);
                content_length--;
            } else {
                break;
            }
        }
        out = body;
        // cerr << "POST DEBUG BODY: " << body << endl;
    } else {

    }
}

bool CutString(std::string &in, const std::string &sep, std::string &out1, std::string &out2) {
    size_t pos = in.find(sep);
    if (std::string::npos != pos) {
        out1 = in.substr(0, pos);
        out2 = in.substr(pos + sep.size());
        return true;
    } else {
        return false;
    }
}

int main() {
    std::string query_string;
    GetQueryString(query_string);
    std::string str1;
    std::string str2;
    if (!CutString(query_string, "&", str1, str2)) {
        std::cerr << "参数Cur失败" << std::endl;
    }
    std::string name1;
    std::string value1;
    if (!CutString(str1, "=", name1, value1)) {
        std::cerr << "参数Cur失败" << std::endl; 
    }
    std::string name2;
    std::string value2;
    if (!CutString(str2, "=", name2, value2)) {
        std::cerr << "参数Cur失败" << std::endl; 
    }   
    std::cout << name1 << "=" << value1 << std::endl;
    std::cout << name2 << "=" << value2 << std::endl;
    std::cerr << name1 << "=" << value1 << std::endl;
    std::cerr << name2 << "=" << value2 << std::endl;
    
    return 0;
}